package controller;

import beans.HttpResultList;

import beans.LogEnum;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import portal.mybatis.dao.User;
import portal.mybatis.dao.service.UserService;
import utils.Log4jInit;
import utils.UserLogUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class UserServlet extends HttpServlet {

    @Autowired
    private UserService userService;
    private HttpResultList result;
    private String currentUserId;


    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        //处理自动装配bean
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        currentUserId = (String) request.getSession().getAttribute("userId");
        result = new HttpResultList();
        String operateType = request.getParameter("operateType");
        try {
            switch (operateType){
                case "add":
                    addUser(request,response);
                    break;
                case "delete":
                    deleteUser(request,response);
                    break;
                case "alter":
                    alterUser(request,response);
                    break;
                case "showAll":
                      showAllUser(request,response);
                    break;
                case "showDetail":
                    showUserDetail(request,response);
                    break;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST参数错误");
        } catch (IOException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("服务器错误");
        }catch (NumberFormatException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST数字错误");
        }
        response.getWriter().print(JSONObject.fromObject(result).toString());

    }

    private void addUser(HttpServletRequest request, HttpServletResponse response) throws NullPointerException, IOException {
        User user=new User();
        user.setUserName(request.getParameter("userName"));
        user.setUserPassword(request.getParameter("userPassword"));
        user.setUserAffiliation(Integer.parseInt(request.getParameter("userAffiliation")));
        user.setUserRole(Integer.parseInt(request.getParameter("userRole")));
        user.setUserEmail(request.getParameter("userEmail"));
        result.setResult(userService.addUser(user)==1);
        // 日志记录
        UserLogUtil.dbLog(LogEnum.user, LogEnum.add,currentUserId,
                LogEnum.user.getValue()+"名称："+user.getUserName());
    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = request.getParameter("userId");
        String userName = userService.getUserNameById(Integer.parseInt(userId));
        if(currentUserId.equals(userId)) request.getSession().invalidate();
        result.setResult(userService.deleteUser(Integer.parseInt(userId)));
        // 日志记录
        UserLogUtil.dbLog(LogEnum.user, LogEnum.delete, currentUserId,
                LogEnum.user.getValue()+"编号："+userId+"，名称："+userName);
    }

    private void alterUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user=new User();
        user.setUserId(Integer.parseInt(request.getParameter("userId")));
        user.setUserName(request.getParameter("userName"));
        user.setUserPassword(request.getParameter("userPassword"));
        user.setUserAffiliation(Integer.parseInt(request.getParameter("userAffiliation")));
        user.setUserRole(Integer.parseInt(request.getParameter("userRole")));
        user.setUserEmail(request.getParameter("userEmail"));
        if(currentUserId.equals(String.valueOf(user.getUserId()))) request.getSession().invalidate();
        result.setResult(userService.updateUser(user));
        // 日志记录
        UserLogUtil.dbLog(LogEnum.user, LogEnum.update, currentUserId,
                LogEnum.user.getValue()+"编号："+user.getUserId());
    }

    private void showAllUser(HttpServletRequest request, HttpServletResponse response) {
//    	Log4jInit.logger.info(System.currentTimeMillis());
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        List<Object> userList = new ArrayList<Object>(userService.selectUserByPage(onePageCount, currentPage));
        result.setResult(userList.size()>0);
        result.setDatas(userList);
        result.setMessage(userService.userPageNum(onePageCount)+"");
    }

    private void showUserDetail(HttpServletRequest request, HttpServletResponse response) {
        int userId = Integer.parseInt(request.getParameter("userId"));
        List<Object>  user = new ArrayList<>();
        user.add(userService.selectByUserId(userId));
        result.setResult(user.size()>0);
        result.setDatas(user);
    }

}
